package routers

import (
	"context"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/route"
	"hertz/api"
	"hertz/pojo"
	myUtils "hertz/utils"
	"strconv"
)

func loadComment(h *route.RouterGroup) {
	comment := h.Group("/comment")
	{
		comment.POST("/action/", addComment)
		comment.GET("/list/", getCommentList)
	}
}

func addComment(c context.Context, ctx *app.RequestContext) {
	// 获取参数
	commentAction := myUtils.GetParamComment(ctx)

	//  鉴权
	user, err := userProvider.Authenticate(c, &api.Token{
		Token:     commentAction.Token,
		Operation: "ADD_COMMENT",
	})
	// token => id -》 return err
	// getRedis(id) is(token) -> return err
	// 查权限 -》 return user{id}， nil
	if err != nil {
		FAIL(ctx, err)
		return
	}

	// 1 - 增加 2 - 删除
	if commentAction.ActionType == "1" {
		add, err := commentProvider.Add(c, &api.Comment{
			UserId:  user.Id,
			VideoId: transInt64(commentAction.VideoId),
			Content: commentAction.CommentText,
		})
		if err != nil {
			FAIL(ctx, err)
		}
		// 转换类型
		OK(ctx, utils.H{"comment": transComment(user, add.GetList()[0])})
	} else {
		commentId, err := strconv.ParseInt(commentAction.CommentId, 10, 64)
		if err != nil {
			FAIL(ctx, err)
		}
		_, err = commentProvider.Del(c, &api.Comment{
			Id: commentId,
		})
		if err != nil {
			FAIL(ctx, err)
		}

		OK(ctx, nil)
	}
}

func getCommentList(c context.Context, ctx *app.RequestContext) {
	// 获取参数
	commentAction := myUtils.GetParamComment(ctx)

	//  鉴权
	user, err := userProvider.Authenticate(c, &api.Token{
		Token:     commentAction.Token,
		Operation: "GET_COMMENT_LIST",
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	commentList, err := commentProvider.Find(c, &api.Comment{
		VideoId: transInt64(commentAction.VideoId),
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	// 转换类型
	var list []pojo.Comment
	for _, value := range commentList.GetList() {
		list = append(list, transComment(user, value))
	}

	OK(ctx, utils.H{"comment_list": list})
}
